import { _decorator, Component, ProgressBar, JsonAsset, director, assetManager } from 'cc';
import { SceneManager } from '../managers/SceneManager';
import { JsonConfigManager } from '../managers/JsonConfigManager';
import { GlobalManager } from '../global/GlobalManager';

const { ccclass, property } = _decorator;

@ccclass('LoadingController')
export class LoadingController extends Component {
    @property(ProgressBar)
    progressBar: ProgressBar = null;

    /**总进度 */
    alltotal = 0;
    /**当前进度 */
    _curloaded = 0;

    start() {
        this.alltotal = GlobalManager.preloadJsonList.length + GlobalManager.scenes.length;
        this.proLoadAll();
    }

    async proLoadAll() {
        // 使用JsonConfigManager加载所有JSON配置
        for (const item of GlobalManager.preloadJsonList) {
            console.log(`[LoadingController] 开始加载JSON配置: ${item.configKey}`);
            
            const config = await JsonConfigManager.instance.loadJsonConfig(item.path, item.configKey, item.isRemote);
            if (config) {
                console.log(`[LoadingController] JSON配置加载成功: ${item.configKey}`);
            } else {
                console.error(`[LoadingController] JSON配置加载失败: ${item.configKey}`);
            }
            
            this.curloaded++;
        }

        for (const sceneCfg of GlobalManager.scenes) {
            await SceneManager.instance.preloadScene(sceneCfg);
            this.curloaded++;
        }
    }

    set curloaded(v: number) {
        this._curloaded = v;
        if (this.progressBar) this.progressBar.progress = this.curloaded > 0 ? this.curloaded / this.alltotal : 1;
        if (this.curloaded / this.alltotal >= 1) {
            const mainScene = GlobalManager.scenes.find(s => s.name === 'Main');
            if (mainScene) {
                SceneManager.instance.loadScene(mainScene);
            }
        }
    }
    get curloaded() {
        return this._curloaded;
    }

    
} 